package com.example.shopdemo.service;

import com.example.shopdemo.dto.ProductCategoryExecution;
import com.example.shopdemo.entity.Product;
import com.example.shopdemo.entity.ProductCategory;
import com.example.shopdemo.enums.ProductCategoryStateEnum;
import com.example.shopdemo.repository.ProductCategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-21
 **/
@Service
public class ProductCategoryServiceImpl {

    @Autowired
    private ProductCategoryRepository productCategoryRepository;

    @Autowired
    private ProductServiceImpl productService;

    public List<ProductCategory> getByShopId(Long shopId){
        return productCategoryRepository.findByShopIdOrderByPriorityDesc(shopId);
    }

    @Transactional
    public ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList) throws RuntimeException{
        if(productCategoryList!=null && productCategoryList.size()>0){
            for(int i=0;i<productCategoryList.size();i++){
                ProductCategory result = productCategoryRepository.save(productCategoryList.get(i));
                if(result==null){
                    return new ProductCategoryExecution(ProductCategoryStateEnum.INNER_ERROR);
                }
            }
            return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
        }
        return  new ProductCategoryExecution(ProductCategoryStateEnum.INNER_ERROR);
    }


    public ProductCategoryExecution deleteProductCategory(Long productCategoryId,Long shopid)throws RuntimeException{
        //将商品product里的类别id置为空，再删除
        try {
            if (productService.getProductListByProductCategoryId(productCategoryId) != null) {
                productService.updateProductCategoryToNull(productCategoryId);
            }
            productCategoryRepository.deleteByProductCategoryIdAndShopId(productCategoryId, shopid);
            return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
        } catch(Exception e){
            throw new RuntimeException("deleteProductCategory error"+e.getMessage());
        }
    }
}
